package com.xiangban.yanglaodajie_platform.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiangban.yanglaodajie_platform.dao.DeliveryAddressMapper;
import com.xiangban.yanglaodajie_platform.dao.GoodsMapper;
import com.xiangban.yanglaodajie_platform.dao.ShopMapper;
import com.xiangban.yanglaodajie_platform.entity.*;
import com.xiangban.yanglaodajie_platform.entity.dto.ShopDto;
import com.xiangban.yanglaodajie_platform.entity.dto.ShopExpandDto;
import com.xiangban.yanglaodajie_platform.entity.res.ApiResultCode;
import com.xiangban.yanglaodajie_platform.exception.BizException;
import com.xiangban.yanglaodajie_platform.utils.CommonUtils;
import com.xiangban.yanglaodajie_platform.utils.HttpClient;
import com.xiangban.yanglaodajie_platform.utils.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.xiangban.yanglaodajie_platform.utils.CommonUtils.BizEmpty;

/**
 * @Author Mr. MaYaYun
 * @Data 2021/2/20 17:16
 */
@Service
public class ShopService {

    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private PageUtil pageUtil;
    @Autowired
    private CommonUtils commonUtils;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private DeliveryAddressMapper deliveryAddressMapper;

    public PageInfo<ShopDto> getList(ShopDto shopDto) {//参数：地区code码和分类id、经纬度
        if (BizEmpty(shopDto.getClassifyId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        PageHelper.startPage(pageUtil.getPage().getPageNum(), pageUtil.getPage().getPageSize());
        if (shopDto.getClassifyId() == 1) {
            int date = DateToNumber(getNowTime());
            shopDto.setDateTime(date);
        }

        //经纬度为空,code不空
        if (shopDto.getLongitude() == null && shopDto.getLatitude() == null){
            //商家位置距离
            Map<String, String> longitudeAndLatitude = getLongitudeAndLatitude(shopDto.getCityCodeCity());
            if (longitudeAndLatitude.keySet().size() > 1) {
                shopDto.setLongitude(new BigDecimal(longitudeAndLatitude.get("longitude")));
                shopDto.setLatitude(new BigDecimal(longitudeAndLatitude.get("latitude")));
            }
        }//经纬度不空，code空
        else {
            Map<String, String> cityCode = getCityCode(shopDto.getLongitude().toString(), shopDto.getLatitude().toString());
            shopDto.setCityCodeCity(Integer.parseInt(cityCode.get("cityCodeCity")));
        }

        //查询商家列表
        List<ShopDto> regionCity = shopMapper.getRegionCity(shopDto);
        if (regionCity != null && regionCity.size() > 0) {
            for (ShopDto dto : regionCity) {
                String[] split1 = new String[0];
                String[] split2 = new String[0];
                String[] split3 = new String[0];
                if (dto.getService() != null && !dto.getService().equals("")) {
                    split1 = dto.getService().split(",");
                }
                if (dto.getShopLabel() != null && !dto.getShopLabel().equals("")) {
                    split2 = dto.getShopLabel().split(",");
                }
                if (dto.getSuperiorService() != null && !dto.getSuperiorService().equals("")) {
                    split3 = dto.getSuperiorService().split(",");
                }
                ArrayList<String> ServiceDto = new ArrayList<>(Arrays.asList(split1));
                ArrayList<String> ShopLabelDto = new ArrayList<>(Arrays.asList(split2));
                ArrayList<String> SuperiorServiceDto = new ArrayList<>(Arrays.asList(split3));


                dto.setServiceDto(ServiceDto);
                dto.setShopLabelDto(ShopLabelDto);
                dto.setSuperiorServiceDto(SuperiorServiceDto);
//                //商家位置距离
//                if (shopDto.getCityCode() != null) {
//                    getLongitudeAndLatitude(shopDto.getCityCode());
//                    BigDecimal longitude = shopDto.getLongitude();//传来的经纬度
//                    BigDecimal latitude = shopDto.getLatitude();
//
//                    BigDecimal ClassLongitude = dto.getLongitude();//商家自己经纬度
//                    BigDecimal ClassLatitude = dto.getLatitude();
//                    //计算商家位置距离保留两位小数（米）
//                    double distance = DateUtil.getDistance(latitude.doubleValue(), longitude.doubleValue(),
//                            ClassLatitude.doubleValue(), ClassLongitude.doubleValue());
//                    String format = new DecimalFormat("#.00").format(distance);
//                    dto.setDistance(Double.parseDouble(format));
//                }
            }
        }
        return new PageInfo<>(regionCity);
    }
    //获取经纬度
    private Map<String, String> getLongitudeAndLatitude(Integer integer) {

        Map<String, String> stringObjectMap = deliveryAddressMapper.selectCityList(integer);//code码查询地区名字
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> stringHashMap = new HashMap<>();
        map.put("key", "6d77b7119a4fb52745394ea5590ccf52");
        map.put("keywords", stringObjectMap.get("districtName"));
        map.put("subdistrict", "0");
        map.put("extensions", "base");
        String s = HttpClient.doGet("https://restapi.amap.com/v3/config/district", map);
        JSONObject jsonObject = JSON.parseObject(s);
        String status = jsonObject.getString("status");
        if (status.equals("1")) {
            Map<String, String> map2 = (Map<String, String>) jsonObject.getJSONArray("districts").get(0);
            String s1 = map2.get("center");
            String[] split = s1.split(",");
            String s2 = split[0];
            String s3 = split[1];
            stringHashMap.put("longitude", s2);
            stringHashMap.put("latitude", s3);
        }
        return stringHashMap;
    }
    //获取城市code
    private Map<String,String> getCityCode(String longitude,String latitude){
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> stringHashMap = new HashMap<>();
        String o = "";
        map.put("key", "6d77b7119a4fb52745394ea5590ccf52");
        map.put("location",longitude+","+latitude);
        map.put("extensions", "base");
        String s = HttpClient.doGet("https://restapi.amap.com/v3/geocode/regeo", map);
        if (s.equals("")){
            throw new BizException(ApiResultCode.SYS_ERROR);
        }
        JSONObject jsonObject = JSON.parseObject(s);
        String status = jsonObject.getString("status");
        if (status.equals("1")) {
            JSONObject regeocode1 = jsonObject.getJSONObject("regeocode");
            JSONObject addressComponent = regeocode1.getJSONObject("addressComponent");
            JSONArray city = null;
            try {
                city = addressComponent.getJSONArray("city");
                o= (String) addressComponent.get("province");
            } catch (Exception e) {
               o= (String) addressComponent.get("city");

            }

            Integer integer = shopMapper.selectCityCodeByName(o);
            if (integer != null){
                stringHashMap.put("cityCodeCity",integer.toString());
            }
        }
        return stringHashMap;
    }

    /**
     * @param shop 参数：分类id、商家id
     * @return商家详情
     */
    public Object getShopInfo(Shop shop) {
        if (BizEmpty(shop.getClassifyId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        if (BizEmpty(shop.getShopId())) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }

        ShopDto shopExpand = shopMapper.selectShopInfo(shop);

        if (shopExpand != null) {
            String[] split1 = new String[0];
            String[] split2 = new String[0];
            String[] split3 = new String[0];

            if (shopExpand.getService() != null && !shopExpand.getService().equals("")) {
                split1 = shopExpand.getService().split(",");
            }
            if (shopExpand.getShopLabel() != null && !shopExpand.getShopLabel().equals("")) {
                split2 = shopExpand.getShopLabel().split(",");
            }
            if (shopExpand.getSuperiorService() != null && !shopExpand.getSuperiorService().equals("")) {
                split3 = shopExpand.getSuperiorService().split(",");
            }
            ArrayList<String> ServiceDto = new ArrayList<>(Arrays.asList(split1));
            ArrayList<String> ShopLabelDto = new ArrayList<>(Arrays.asList(split2));
            ArrayList<String> SuperiorServiceDto = new ArrayList<>(Arrays.asList(split3));

            shopExpand.setServiceDto(ServiceDto);
            shopExpand.setShopLabelDto(ShopLabelDto);
            shopExpand.setSuperiorServiceDto(SuperiorServiceDto);
        }
        ShopExpandDto shopExpandDto = new ShopExpandDto();
        BeanUtils.copyProperties(shopExpand, shopExpandDto);
        if (shopExpand.getIsActivity() == 2) {
            //获取关于我们
            ShopExpand shopExpand1 = shopMapper.selectShopExpand(shop);
            if (shopExpand1!=null){
                List<String> parse = (List<String>) JSON.parse(shopExpand1.getSynopsisImage());
                shopExpandDto.setSynopsisImages(parse);
                shopExpandDto.setSynopsisText(shopExpand1.getSynopsisText());
                shopExpandDto.setReportRequire(shopExpand1.getReportRequire());
                shopExpandDto.setEmail(shopExpand1.getEmail());
                shopExpandDto.setUrl(shopExpand1.getUrl());
                shopExpandDto.setPublicUrl(shopExpand1.getPublicUrl());
                shopExpandDto.setPublicUrlLogo(shopExpand1.getPublicUrlLogo());
                shopExpandDto.setPublicUrlText(shopExpand1.getPublicUrlText());

            }



            //获取领导班子
            List<Leader> leader = getLeader(shop.getShopId());
            shopExpandDto.setLeaderList(leader);
            //获取学校荣誉
            List<Honor> honor = getHonor(shop.getShopId());
            shopExpandDto.setHonorList(honor);

        }
        return shopExpandDto;
    }

    private List<Leader> getLeader(Integer id) {
        return shopMapper.selectLeaderList(id);
    }

    private List<Honor> getHonor(Integer id) {
        return shopMapper.selectHonorList(id);
    }

    /**
     * @param orders 参数：商家id
     * @return店铺订单(商家端)
     */
    public PageInfo<Orders> getShopOrders(Orders orders) {
        if (BizEmpty(commonUtils.getShopId(request))) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        PageHelper.startPage(pageUtil.getPage().getPageNum(), pageUtil.getPage().getPageSize());
        List<Orders> ordersList = shopMapper.getOrdersList(orders);
        for (Orders orders1 : ordersList) {
            String goodSku = orders1.getGoodSku();
            JSONArray objects = JSON.parseArray(goodSku);
            ObjectMapper objectMapper = new ObjectMapper();
            ArrayList<Object> list = new ArrayList<>();
            for (int i = 0; i < objects.size(); i++) {
                Object o = objects.get(i);
                Map map1 = objectMapper.convertValue(o, Map.class);
                int goodsId = (int) map1.get("goodsId");
                Goods info = goodsMapper.findInfo(goodsId);
                map1.put("image", info.getLogo());
                list.add(map1);
            }
            orders1.setGoodSkuDto(list);
            orders1.setGoodSku(null);
        }

        return new PageInfo<>(ordersList);
    }

    /**
     * @param orders 参数：商家id
     * @return订单类型数量(商家端)
     */
    public Map<String, Object> OrdersClassifyNumber(Orders orders) {
        if (BizEmpty(commonUtils.getShopId(request))) {
            throw new BizException(ApiResultCode.PARAMETER_DEFICIENCY);
        }
        HashMap<String, Object> map = new HashMap<>();
        orders.setShopId(Integer.parseInt(commonUtils.getShopId(request)));
        ShopDto waitTakes = shopMapper.findWaitTakes(orders);//查询待配送数量
        if (waitTakes == null) {
            map.put("waitTakes", 0);
        } else {
            map.put("waitTakes", waitTakes.getWaitTakes());
        }
        ShopDto waitConfirm = shopMapper.findWaitConfirm(orders);//查询待确认数量
        if (waitConfirm == null) {
            map.put("waitConfirm", 0);
        } else {
            map.put("waitConfirm", waitConfirm.getWaitConfirm());
        }
        ShopDto waitRefund = shopMapper.findWaitRefund(orders);//查询待退款数量
        if (waitRefund == null) {
            map.put("waitRefund", 0);
        } else {
            map.put("waitRefund", waitRefund.getWaitRefund());
        }
        ShopDto waitDestroy = shopMapper.findWaitDestroy(orders);//查询待核销数量
        if (waitDestroy == null) {
            map.put("waitDestroy", 0);
        } else {
            map.put("waitDestroy", waitDestroy.getWaitDestroy());
        }
        ShopDto dto = shopMapper.selectWaitGet(orders);//查询待自提
        if (dto == null) {
            map.put("waitGet", 0);
        } else {
            map.put("waitGet", dto.getWaitGet());
        }

        return map;
    }

    public String getNowTime() {
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
        return simpleDateFormat.format(date);
    }

    public int DateToNumber(String date) {
        String[] replace = date.split(":");
        return (Integer.parseInt(replace[0])) * 60 + Integer.parseInt(replace[1]);
    }

//    public Object getShopData(Object o) {
//        shopMapper.getShopData();
//    }
}
